package cc.eddic.examinationsystem.service;

import cc.eddic.examinationsystem.dto.ThymeleafUserDetails;
import cc.eddic.examinationsystem.repository.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final StudentRepository userRepository;

    @Autowired
    public UserDetailsServiceImpl(StudentRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (log.isDebugEnabled()) log.debug("username : {}", username);

        long empNo;
        try {
            empNo = Long.parseLong(username);
        } catch (NumberFormatException e) {
            val msg = String.format("无效的员工编号 %s 。", username);
            throw new UsernameNotFoundException(msg);
        }

        val msg = String.format("用户 %s 未找到。", username);
        val user = userRepository.findByEmployeeNo(empNo)
                .orElseThrow(() -> new UsernameNotFoundException(msg));

        if (log.isDebugEnabled())
            log.debug("mobile = {}, createdOn = {}, id = {}", user.getMobile(), user.getCreatedOn(), user.getId());
        return new ThymeleafUserDetails(user);
    }

}
